<script setup>
import {ref} from 'vue'
import {useRouter} from "vue-router";
import {_login} from "../api/user.js";
import {errorMsg, succesMsg} from "../util/box.js";
import {setToken} from "../util/auth.js";
import {useUserStore} from "../store/user.js";

const router = useRouter()
const userStore = useUserStore()

const loginUser = ref({
  username: "",
  password: "",
})

const login = () => {
  _login(loginUser.value).then(res => {
    if ( res.success ) {
      userStore.login(res.data.user)
      setToken(res.data.user.token)
      router.push({path: '/index'})
      succesMsg("登录成功")
    } else {
      errorMsg("用户名或密码错误")
    }
  })
}

</script>

<template>
  <div class="login-form">
    <el-card style="width: 40%">
      <el-form
          label-position="right"
          label-width="auto"
          :model="loginUser"
      >
        <el-form-item label="用户名">
          <el-input v-model="loginUser.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input type="password" v-model="loginUser.password" />
        </el-form-item>
      </el-form>
      <el-space class="login-button">
        <el-link style="margin-right: 20px; color: blue" @click="router.push({path: '/register'})">没有账号, 去注册</el-link>
        <el-button @click="login">登录</el-button>
      </el-space>
    </el-card>
  </div>
</template>

<style scoped>
.login-form {
  display: flex;
  //width: 50%;
  margin-top: 10%;
  justify-content: center;
  align-items: center;
}
.login-button {
  float: right;
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>